package com.kk.springboot_002.controller;

import com.kk.springboot_002.pojo.User;
import com.kk.springboot_002.pojo.dto.RegisterDto;
import com.kk.springboot_002.pojo.dto.UserDto;
import com.kk.springboot_002.service.MyUserDetailsService;
import com.kk.springboot_002.service.UserService;
import com.kk.springboot_002.util.JwtUtil;
import com.kk.springboot_002.util.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/auth")

public class AuthController {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Response<?> createAuthenticationToken(@RequestBody UserDto userDto) {
        try {
            // 1. 调用 AuthenticationManager 进行身份验证
            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(userDto.getName(), userDto.getPassword())
            );
        } catch (AuthenticationException e) {
            // 认证失败，返回401状态码和错误信息
            return Response.error(401, "用户名或密码错误");
        }
        // 2. 认证成功后，加载用户详情并生成JWT令牌
        final UserDetails userDetails = myUserDetailsService.loadUserByUsername(userDto.getName());
        final String jwt = jwtUtil.generateToken(userDetails);
        log.info("Token：{}", jwt);

        // 3. 将令牌封装成JSON格式返回给客户端
        Map<String, String> response = new HashMap<>();
        response.put("token", jwt);
        return Response.success(response);
    }

    @PostMapping("/register")
    public Response<?> registerUser(@RequestBody RegisterDto registerDto) {
        // 检查用户名是否存在
        if(userService.findByUserName(registerDto.getName()) != null){
            return Response.error(400, "用户名已存在");
        }
        // 创建用户
        User user = new User(null, registerDto.getName(),
                passwordEncoder.encode(registerDto.getPassword()), registerDto.getEmail(), null);
        // 保存用户
        userService.save(user);
        return Response.success("注册成功",null);
    }
}
